package com.ciwong.epaper.modules.pad.contentprovider;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.LoginInfo;
import com.ciwong.epaper.modules.pad.ui.PadLoginDialogActivity;
import com.ciwong.epaper.ui.NewLoginActivity;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.mobilelib.bean.DetailUserInfo;
import com.ciwong.mobilelib.utils.ThreadTask;

import java.io.Serializable;

public class LoginToken implements Serializable {
    public static final String LOGIN_FROM = "LOGIN_FROM";
    public static final String LOGIN_FROM_APPMARKET = "LOGIN_FROM_APPMARKET";
    public static final String LOGIN_FROM_HD = "LOGIN_FROM_HD";

    public static final int REQUEST_CODE_TO_LAUNCHER_LOGIN = 1018;
    public static final int REQUEST_CODE_TO_LAUNCHER_LOGIN_OUT = 1019;

    private static final String TAG = "LoginToken";
    public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
    public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
    public static final String MIME_ITEM = "vnd.ciwong.sqlite";

    public static final String MIME_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + MIME_ITEM;
    public static final String MIME_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/" + MIME_ITEM;

    public static String AUTHORITY = "com.ciwong.newspaperhd.login.contentprovider.sqlite";
    public static final String PATH_SINGLE = TokenContentProvider.DB_TABLE + "/#";
    public static final String PATH_MULTIPLE = TokenContentProvider.DB_TABLE;
    public static String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MULTIPLE;
    public static Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING);

    public static final String KEY_ID = "_id";
    public static final String KEY_REFTOKEN = "reftoken";
    public static final String KEY_TOKEN = "token";
    public static final String KEY_EXPIRESIN = "expresin";

    public static final String KEY_USER_ID = "userid";
    public static final String KEY_AVATAR = "avatar";
    public static final String KEY_REAL_NAME = "realName";
    public static final String KEY_NICK_NAME = "nickName";

    public static final String KEY_MOBILE = "mobile";
    public static final String KEY_USER_ROLE = "userRole";

    public static final String KEY_SCHOOL_ID = "schoolId";
    public static final String KEY_SCHOOL_NAME = "schoolName";
    public static final String KEY_SCHOOL_AREA = "schoolArea";
    public static final String KEY_SCHOOL_AREA_NAME = "schoolAreaName";

    public static final String KEY_CLASS_ID = "classId";
    public static final String KEY_CLASS_NAME = "className";


    public static final String ACTION_KEY_RELOGIN = "ACTION_KEY_RELOGIN";

    public static String ACTION_LOGIN_SUCCESS = "ACTION_LOGIN_SUCCESS";

    public static String ACTION_EXIT_LOGIN = "ACTION_EXIT_LOGIN";

    public static String ACTION_BIND_PHONE_SUCCESS = "ACTION_BIND_PHONE_SUCCESS";
    public static String IS_BIND_PHONE = "IS_BIND_PHONE";

    private String id;

    private String reftoken;

    private String token;


    private String userid;


    /**
     * 用户头像
     */
    private String avatar;

    /**
     * 真实姓名
     */
    private String realName;

    /**
     * 昵称
     */
    private String nickName;

    /**
     * 用户性别
     */

    private String mobile;

    private String expresin;
    private int userRole;
    private int schoolId;
    private String schoolName;

    private String schoolArea;
    private String schoolAreaName;

    private int classId;
    private String className;

    public int getSchoolId() {
        return schoolId;
    }

    public void setSchoolId(int schoolId) {
        this.schoolId = schoolId;
    }

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public String getSchoolArea() {
        return schoolArea;
    }

    public void setSchoolArea(String schoolArea) {
        this.schoolArea = schoolArea;
    }

    public String getSchoolAreaName() {
        return schoolAreaName;
    }

    public void setSchoolAreaName(String schoolAreaName) {
        this.schoolAreaName = schoolAreaName;
    }

    public int getClassId() {
        return classId;
    }

    public void setClassId(int classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public int getUserRole() {
        return userRole;
    }

    public void setUserRole(int userRole) {
        this.userRole = userRole;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }


    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getReftoken() {
        return reftoken;
    }

    public void setReftoken(String reftoken) {
        this.reftoken = reftoken;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getExpresin() {
        return expresin;
    }

    public void setExpresin(String expresin) {
        this.expresin = expresin;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }


    /**
     * pad环境 专用
     */
    public static LoginToken queryTokenAndUserInfo(ContentResolver contentResolver) {
        //从别的应用launcher获取
        LoginToken loginToken = null;
        Cursor cursor = null;
        try {
            cursor = contentResolver.query(LoginToken.CONTENT_URI, new String[]{LoginToken.KEY_ID, LoginToken.KEY_REFTOKEN, LoginToken.KEY_TOKEN, LoginToken.KEY_USER_ID, LoginToken.KEY_AVATAR, LoginToken.KEY_REAL_NAME, LoginToken.KEY_NICK_NAME, LoginToken.KEY_MOBILE, LoginToken.KEY_USER_ROLE, LoginToken.KEY_EXPIRESIN
                            , loginToken.KEY_SCHOOL_ID, LoginToken.KEY_SCHOOL_NAME, loginToken.KEY_SCHOOL_AREA, loginToken.KEY_SCHOOL_AREA_NAME, LoginToken.KEY_CLASS_ID, LoginToken.KEY_CLASS_NAME},
                    null, null, null);
        } catch (Exception e) {

        }

        if (cursor == null) {
            return null;
        }
        if (cursor.getCount() <= 0) {
            //跳转launcher  登录
            cursor.close();
            return null;
        }
        try {
            cursor.moveToFirst();

            loginToken = new LoginToken();
            loginToken.setId(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_ID)));
            loginToken.setReftoken(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_REFTOKEN)));
            loginToken.setToken(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_TOKEN)));
            loginToken.setUserid(AESCBCUtil.decrypt(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_USER_ID)), AESCBCUtil.AESCBC_HEX));
            loginToken.setAvatar(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_AVATAR)));
            loginToken.setRealName(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_REAL_NAME)));
            loginToken.setNickName(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_NICK_NAME)));
            loginToken.setMobile(AESCBCUtil.decrypt(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_MOBILE)), AESCBCUtil.AESCBC_HEX));
            loginToken.setUserRole(cursor.getInt(cursor.getColumnIndex(LoginToken.KEY_USER_ROLE)));
            loginToken.setExpresin(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_EXPIRESIN)));

            loginToken.setSchoolId(cursor.getInt(cursor.getColumnIndex(LoginToken.KEY_SCHOOL_ID)));
            loginToken.setSchoolName(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_SCHOOL_NAME)));
            loginToken.setSchoolArea(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_SCHOOL_AREA)));
            loginToken.setSchoolAreaName(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_SCHOOL_AREA_NAME)));

            loginToken.setClassId(cursor.getInt(cursor.getColumnIndex(LoginToken.KEY_CLASS_ID)));
            loginToken.setClassName(cursor.getString(cursor.getColumnIndex(LoginToken.KEY_CLASS_NAME)));

        } catch (Exception e) {

        } finally {
            cursor.close();
        }

        return loginToken;
    }

    /**
     */
    public static void updateProviderToken(ContentResolver contentResolver, LoginToken loginToken) {
        try {
            ContentValues values = new ContentValues();
            values.put(LoginToken.KEY_TOKEN, loginToken.getToken());
            values.put(LoginToken.KEY_REFTOKEN, loginToken.getReftoken());
            Uri uri = Uri.parse(LoginToken.CONTENT_URI_STRING + "/" + loginToken.getId());
            int result = contentResolver.update(uri, values, null, null);
            String msg = "更新ID为" + loginToken.getId() + "的数据" + (result > 0 ? "成功" : "失败");
            Log.e(TAG, "#####updateProviderToken########" + msg);
        } catch (Exception e) {

        }

    }

    public static void updateSchoolId(ContentResolver contentResolver, LoginToken loginToken) {
        try {
            ContentValues values = new ContentValues();
            values.put(LoginToken.KEY_SCHOOL_ID, loginToken.getSchoolId());
            Uri uri = Uri.parse(LoginToken.CONTENT_URI_STRING + "/" + loginToken.getId());
            int result = contentResolver.update(uri, values, null, null);
            String msg = "更新ID为" + loginToken.getId() + "的数据" + (result > 0 ? "成功" : "失败");
            Log.e(TAG, "#####updateSchoolId########" + msg);
        } catch (Exception e) {
            Log.e(TAG, "#####updateSchoolId######## 异常==" + e.getMessage());
        }

    }


    public static void cleanLocalToken(final ContentResolver contentResolver) {
        //保存或者更新到contentProvider 中，用于其他应用共享
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Cursor cursor = contentResolver.query(LoginToken.CONTENT_URI, new String[]{LoginToken.KEY_ID, LoginToken.KEY_REFTOKEN, LoginToken.KEY_TOKEN}, null, null, null);
                    Log.d(TAG, "数据库：" + String.valueOf(cursor.getCount()) + "条记录");
                    if (cursor.getCount() > 0) {
                        //删除全部重新添加，因为只需要一条记录
                        Log.d(TAG, "删除全部重新添加");
                        contentResolver.delete(LoginToken.CONTENT_URI, null, null);
                    }
                    cursor.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, ThreadTask.ThreadPeriod.PERIOD_MIDDLE);
    }

    /**
     * pad环境 专用
     */
    public static void goToUnifiedLogin(Activity activity) {
        try {
            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.ciwong.newspaperhd", "com.ciwong.epaper.modules.pad.ui.PadLoginDialogActivity");
            intent.setComponent(comp);
            intent.putExtra("INTENT_FLAG_TYPE", 1001);
            activity.startActivityForResult(intent, REQUEST_CODE_TO_LAUNCHER_LOGIN);
        } catch (Exception e) {

        }
    }

    public static void goToUnifiedLogin2(Context context) {
        try {
            Intent intent;
            if ("com.ciwong.newspaperhd".equals(context.getPackageName())) {
                intent = new Intent(context, PadLoginDialogActivity.class);
            } else {
                intent = new Intent(context, NewLoginActivity.class);
            }
            intent.putExtra("INTENT_FLAG_TYPE", 1001);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {

        }
    }

    public static void exitLogin(Context context) {
        LoginToken.cleanLocalToken(context.getContentResolver());
        Intent intent = new Intent(LoginToken.ACTION_EXIT_LOGIN);
        context.sendBroadcast(intent);
    }

    public static void saveTokenInfoToContentProividerByPad(EApplication application, LoginInfo loginBean, DetailUserInfo detailUserInfo) {
        //保存或者更新到contentProvider 中，用于其他应用共享
        ContentResolver resolver = application.getBaseContext().getContentResolver();
        Cursor cursor = null;
        try {
            cursor = resolver.query(LoginToken.CONTENT_URI, new String[]{LoginToken.KEY_ID, LoginToken.KEY_REFTOKEN, LoginToken.KEY_TOKEN}, null, null, null);
        } catch (Exception e) {

        }

        if (cursor != null) {
            Log.d(TAG, "数据库：" + String.valueOf(cursor.getCount()) + "条记录");
            if (cursor.getCount() > 0) {
                //删除全部重新添加，因为只需要一条记录
                try {
                    resolver.delete(LoginToken.CONTENT_URI, null, null);
                } catch (Exception e) {

                }
            }
            cursor.close();
        }


        //添加操作
        ContentValues values = new ContentValues();
        values.put(LoginToken.KEY_REFTOKEN, loginBean.getRefreshToken());
        values.put(LoginToken.KEY_TOKEN, loginBean.getAccessToken());
        values.put(LoginToken.KEY_USER_ID, AESCBCUtil.encrypt(loginBean.getUserId(), AESCBCUtil.AESCBC_HEX));
        values.put(LoginToken.KEY_AVATAR, loginBean.getAvatar());
        values.put(LoginToken.KEY_REAL_NAME, loginBean.getRealName());
        values.put(LoginToken.KEY_MOBILE, AESCBCUtil.encrypt(loginBean.getMobile(), AESCBCUtil.AESCBC_HEX));
        if (detailUserInfo != null) {
            values.put(LoginToken.KEY_USER_ROLE, detailUserInfo.getUserRole());
        } else {
            //默认是学生
            values.put(LoginToken.KEY_USER_ROLE, 1);
        }
        values.put(LoginToken.KEY_EXPIRESIN, loginBean.getExpiresIn());

        if (detailUserInfo != null) {
            values.put(LoginToken.KEY_SCHOOL_ID, detailUserInfo.getSchoolId());
            values.put(LoginToken.KEY_SCHOOL_NAME, detailUserInfo.getSchoolName());
            values.put(LoginToken.KEY_SCHOOL_AREA, detailUserInfo.getSchoolArea());
            values.put(LoginToken.KEY_SCHOOL_AREA_NAME, detailUserInfo.getSchoolAreaName());
            values.put(LoginToken.KEY_CLASS_ID, detailUserInfo.getClassId());
            values.put(LoginToken.KEY_CLASS_NAME, detailUserInfo.getClassName());

        }

        try {
            Uri newUri = resolver.insert(LoginToken.CONTENT_URI, values);
            Log.d(TAG, "添加成功，URI:" + newUri);
        } catch (Exception e) {

        }

    }

}
